package com.dongdong.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.dongdong.api.OrderItemAPI;
import com.dongdong.config.AlipPayConfig2;
import com.dongdong.em.Result;
import com.dongdong.em.ResultEnum;
import com.dongdong.vo.RefundQueryVO;
import com.dongdong.vo.TradeQueryVO;
import com.dongdong.vo.TradeRefundVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("alipay")
public class AliPayController {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderItemAPI orderItemAPI;

    //付款
    @PostMapping("ali")
    public String AliPay(@RequestParam String out_trade_no,@RequestParam String total_amount,@RequestParam String subject) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(AlipPayConfig2.notify_url);//"https://748be9f2.r7.cpolar.top/notify/notifyUrl"
//同步跳转地址，仅支持http/https
        request.setReturnUrl(AlipPayConfig2.return_url);//"https://748be9f2.r7.cpolar.top/notify/returnUrl"

/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", out_trade_no);
//支付金额，最小值0.01元
        bizContent.put("total_amount", total_amount);
//订单标题，不可使用特殊符号
        bizContent.put("subject", subject);
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }


    //交易查询
    @GetMapping("tradeQuery")
    public Result tradeQuery(String out_trade_no) {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);//流水号
//bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            String body = response.getBody();

            //封装到VO类
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object alipay_trade_query_response = jsonObject.get("alipay_trade_query_response");

            TradeQueryVO queryVO = JSON.parseObject(JSONObject.toJSONString(alipay_trade_query_response), TradeQueryVO.class);

            return Result.OK().setData(queryVO);
        } else {
            System.out.println("调用失败");
            return Result.ERROR();
        }
    }


    //交易退款
    @GetMapping("tradeRefund")
    public Result tradeRefund( String trade_no,String refund_amount,String out_request_no) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);//商户订单编号
        bizContent.put("refund_amount", refund_amount);//退款金额
        bizContent.put("out_request_no", out_request_no);//交退款请求号    交易订单号   商户订单号

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            String body = response.getBody();

            //封装进VO类
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object alipay_trade_query_response = jsonObject.get("alipay_trade_refund_response");//官网json格式上方有一个集合
            TradeRefundVO refundVO = JSON.parseObject(JSONObject.toJSONString(alipay_trade_query_response), TradeRefundVO.class);

            //判断退款状态
            if (!Objects.equals(refundVO.getFund_change(), "Y")) {
                //退款失败
                RefundQueryVO refundQueryVO = refundQuery(trade_no, out_request_no);//订单号    批次号（商户订单号）
                if (!Objects.equals(refundQueryVO.getRefund_status(), "REFUND_SUCCESS")) {
                    return Result.ZHRESPONSE(ResultEnum.REFUND_ERROR);//退款失败
                } else {
                    return Result.ZHRESPONSE(ResultEnum.REFUND_REPETITION_ERROR);//退款重复
                }
            } else {
                //退款成功  根据流水号查询 增加批次号   批次号是唯一的可以使用idwoker生成   调用orderitem接口  如果查询到了就修改批次号  其实就是增加批次号
                int i = orderItemAPI.orderItemGetOrderNoByOutRequestNo(trade_no);//流水号
                if (i > 0) {
                    return Result.ZHRESPONSE(ResultEnum.REFUND_SUCCESS);//退款成功并且修改状态  增加 批次号成功
                }
            }
            // TODO: 2023/6/1  根据批次号修改orderitem信息   修改状态为退款  重复   增加批次号
            return Result.OK().setData(refundVO);
        } else {
            System.out.println("调用失败");

            return Result.ERROR();
        }
    }


    //交易退款查询接口
    public RefundQueryVO refundQuery(@RequestParam String trade_no, @RequestParam String out_request_no) {//流水号   （批次号）商户订单号
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);//流水号
        bizContent.put("out_request_no", out_request_no);//商户订单编号（批次号（退款成功才有））

        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            String body = response.getBody();

            //封装到VO类中
            JSONObject jsonObject = JSONObject.parseObject(body);
            String refundQueryResponse = JSONObject.toJSONString(jsonObject.get("alipay_trade_fastpay_refund_query_response"));
            RefundQueryVO refundQueryVO = JSONObject.parseObject(refundQueryResponse, RefundQueryVO.class);

            return refundQueryVO;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
